// middleware.ts
import {NextRequest, NextResponse} from "next/server";
import NextAuth from "next-auth";
import {apiAuthPrefix, authRoutes, DEFAULT_LOGIN_REDIRECT, publicRoutes} from "@/routes";
import {authOptions} from "@/auth.config";
// import middleware from "next-auth/middleware";
// export {default} from "next-auth/middleware";

// 中间件, 防止未登录用户访问受保护路由
// export function middleware(req: NextRequest) {
//     // 重定向到redirect
//     // return NextResponse.redirect(new URL('/api/auth/signin', req.url))
//
//     const {nextUrl} = req
//     const isLoggedIn = !!req.auth
//
//     const isApiAuthRoute = nextUrl.pathname.startsWith(apiAuthPrefix)
//     const isPublicRoute = publicRoutes.includes(nextUrl.pathname)
//     const isAuthRoute = authRoutes.includes(nextUrl.pathname)
//
//     if (isApiAuthRoute) {
//         return null
//     }
//
//     if (isAuthRoute) {
//         if (isLoggedIn) {
//             return NextResponse.redirect(new URL(DEFAULT_LOGIN_REDIRECT), nextUrl)
//         }
//         return null
//     }
//
//     if (!isLoggedIn && !isPublicRoute) {
//         return NextResponse.redirect(new URL('/auth/login', nextUrl))
//     }
//
//     return null
// }

// 未登录会跳转到登录页
// export default middleware

export const config = {
    // 哪些路由被保护
    // 还可以用*, +, ?
    // matcher: ['/users/:id*','/']
    matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)']
}

const {auth} = NextAuth(authOptions)
// @ts-ignore
export default auth((req) => {

    // 重定向到redirect
    // return NextResponse.redirect(new URL('/api/auth/signin', req.url))

    const {nextUrl} = req
    const isLoggedIn = !!req.auth

    const isApiAuthRoute = nextUrl.pathname.startsWith(apiAuthPrefix)
    const isPublicRoute = publicRoutes.includes(nextUrl.pathname)
    const isAuthRoute = authRoutes.includes(nextUrl.pathname)

    if (isApiAuthRoute) {
        return null
    }

    if (isAuthRoute) {
        if (isLoggedIn) {
            return NextResponse.redirect(new URL(DEFAULT_LOGIN_REDIRECT, nextUrl))
        }
        return null
    }

    if (!isLoggedIn && !isPublicRoute) {
        return NextResponse.redirect(new URL('/auth/login', nextUrl))
    }

    return null
})
